import hashlib
from block import models
import json
from block.BlockChain import str_to_dict_method


def Block(data, prev_hash):
    d1 = {
        "data": data,
        "prev_hash": prev_hash,
        "nonce": 0,
    }
    return d1
    # 计算区块的哈希值


def hash(block):
    message = hashlib.sha256()
    message.update(str(block["data"]).encode('utf-8'))
    message.update(str(block["nonce"]).encode('utf-8'))
    print(type(message.hexdigest()))
    return message.hexdigest()


def create_generate_block():
    """
    生成创世区块，创世区块是第一个区块，无父区块哈希
    :return:
    """
    block = Block("Genesis Block", "")
    powork = ProofOfWork(block)
    nonce, digest = powork.mine()
    block["nonce"] = nonce
    return block


def add_block(data):
    """
    添加区块
    """
    prev = models.Blockinfo.objects.all().last()
    prev_blockinfo = prev.block
    prev_block = str_to_dict_method.str_to_dict(prev_blockinfo)
    new_block = Block(str([data]), hash(prev_block))
    powork = ProofOfWork(new_block)
    nonce, digest = powork.mine()
    new_block["nonce"] = nonce
    return new_block


class ProofOfWork:
    """
    工作量证明
    """

    def __init__(self, block):
        self.block = block

    def mine(self):
        """
        挖矿函数
        :return:
        """
        i = 0
        prefix = "0000"

        while True:
            nonce = str(i)
            message = hashlib.sha256()
            message.update(str(self.block["data"]).encode('utf-8'))
            message.update(str(nonce).encode('utf-8'))
            digest = message.hexdigest()
            if digest.startswith(prefix):
                print(nonce, digest)
                return nonce, digest
            i += 1


# 根据条件获取区块：
def get_block(account):
    b = models.Blockinfo.objects.filter(account=account).first()
    return b

def get_block_all():
    form = models.Blockinfo.objects.all()
    return form

def get_some_block(value):
    form = models.Blockinfo.objects.filter(account__startswith=value)
    return form

# 获取下一个区块存储的prev_hash
def get_nextblock_prevhash(id):
    next_blockinfo = models.Blockinfo.objects.filter(id=id).first()
    next_block = str_to_dict_method.str_to_dict(next_blockinfo.block)
    pre_hash = next_block["prev_hash"]
    return pre_hash


# 获取最后一个区块
def get_last_block():
    last_block = models.Blockinfo.objects.all().last()
    return last_block


# 将数据存入BlockInfo数据库中：
"""
account 是账号
name 是名字
"""
def save_to_BlockInfo(account,name, new_block):
    block = json.dumps([new_block])
    models.Blockinfo.objects.create(account=account,name=name, block=block)


def get_count(page_size):
    count = models.Blockinfo.objects.all().count()-1
    total_page_count , div = divmod(count,page_size)
    if div:
        total_page_count+=1
    return total_page_count